from django.shortcuts import render
from django.views import View
from django import http
from django.core.paginator import Paginator, EmptyPage

from contents.utils import get_categories
from .models import GoodsCategory
from .utils import get_breadcrumb


class ListView(View):
    """商品列表界面"""

    def get(self, request, category_id, page_num):

        # 校验category_id是否真实有效
        try:
            cat3 = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('category_id不存在')

        # 包装面包屑数据

        # cat1 = cat3.parent.parent
        # cat1.url = cat1.goodschannel_set.all()[0].url
        # breadcrumb = {
        #     'cat1': cat1,
        #     'cat2': cat3.parent,
        #     'cat3': cat3
        # }
        # 获取sort查询参数的值
        sort = request.GET.get('sort', 'default')
        if sort == 'price':  # 以价格排序
            sort_field = '-price'
        elif sort == 'hot':
            sort_field = '-sales'
        else:
            sort = 'default'
            sort_field = '-create_time'


        # 查询出指定三级类型下的所有要展示的sku商品
        sku_qs = cat3.sku_set.filter(is_launched=True).order_by(sort_field)
        # total_count = sku_qs.count()
        # page = 5  # 每页显示5条
        # page_num = int(page_num)
        # total_page = total_count // page + ((total_count % page) and 1)
        # page_skus = sku_qs[(page_num - 1) * page: page_num * page]
        # 创建分页器 (要分页的所有数据, 每页显示多少条数据)
        paginator = Paginator(sku_qs, 5)
        total_page = paginator.num_pages  # 获取总页数
        try:
            page_skus = paginator.page(page_num)  # 获取指定页的数据
        except EmptyPage:
            return http.HttpResponseForbidden('没有指定页')


        context = {

            'categories': get_categories(),  # 商品分类数据
            'breadcrumb': get_breadcrumb(cat3),   # 面包屑导航数据
            'category': cat3,  # 三级类别
            'page_skus': page_skus,   # 指定页中所有sku商品数据
            'page_num': page_num,  # 当前显示第几页
            'total_page': total_page,  # 总页数
            'sort': sort,  # 当前是按照什么规则排序
        }
        return render(request, 'list.html', context)
